﻿using System.Collections.Generic;
using System.Linq;
using Store.Web.Models;

namespace Store.Web.Services
{
    public class ProductService
    {
        #region Private Fields

        private readonly string _connectionString;
        
        #endregion

        #region Ctors

        public ProductService(string connectionString)
        {
            _connectionString = connectionString;
        }
        
        #endregion

        #region Public Methods

        public List<Models.Product> GetProducts(int number)
        {
            if (number <= 0)
            {
                return GetProducts();
            }
            else
            {
                using (var storeDbContext = new StoreDbContext(_connectionString))
                {
                    return storeDbContext.Products.OrderBy(p => p.Title).Take(number).ToList();
                }
            }
        }

        public List<Models.Product> GetProducts()
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                return storeDbContext.Products.OrderBy(p => p.Title).ToList();
            }
        }

        public Product GetProduct(int id)
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                return storeDbContext.Products.FirstOrDefault(p => p.Id == id);
            }
        }

        public void UpdateProduct(Product product)
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                storeDbContext.Entry<Product>(product).State = System.Data.EntityState.Modified;
                storeDbContext.SaveChanges();
            }
        }

        public void AddProduct(Product product)
        {
            using (var storeDbContext = new StoreDbContext(_connectionString))
            {
                storeDbContext.Entry<Product>(product).State = System.Data.EntityState.Added;
                storeDbContext.SaveChanges();
            }
        }

        #endregion
    }
}